import socketev, socket, threading, sppt, plugin, time

class listener(threading.Thread):
	def __init__(self, port=6112, protocol="bnet.py"):
		self.port = port
		self.listen = True
		threading.Thread.__init__(self)
		self.setDaemon(True)
		self.protocolName = protocol
		self.client = None
		self.looping = True
		self.proto = plugin.protocol(self.protocolName)
		self.start()
		
	def addressparse(self, address):
		if type(address) == type(()):
			ip = address[0]
		else:
			ip = address
		return ip
		
	def BlockSend(self):
		self.client.block = True
		
	def OnSending(self, owner, data):
		sppt.write("Sending (client) [%s]: %i" % (self.protocolName, len(data)))
		self.proto.Invoke("OnSending", [owner, data])
		
	def OnSend(self, owner, data):
		sppt.write("Send (client) [%s]: %i" % (self.protocolName, len(data)))
		self.proto.Invoke("OnSend", [owner, data])
		
	def OnRecv(self, owner, data):
		sppt.write("Recv (client) [%s]: %i" % (self.protocolName, len(data)))
		self.proto.Invoke("OnRecv", [owner, data])
	
	def OnStart(self):
		sppt.write("Started (client) [%s]: -" % self.protocolName)
		self.proto.Invoke("OnStart", [self])
	
	def OnDisconnect(self, owner, text):
		sppt.write("Disconnect (client) [%s]: %s" % (self.protocolName, text))
		self.proto.Invoke("OnDisconnect", [owner, text])
	
	def run(self):
		#this loop listens for new connections
		sppt.write("Listening for new connections with port %i and protocol %s." % (self.port, self.protocolName))
		while self.listen == True:
			s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			s.bind(('', self.port))
			s.listen(1)
			conn, addr = s.accept()
			self.OnStart()
			time.sleep(0.04)
			self.listen = False
			while (self.proto.p.client == None):
				#block while the proto sets itself up
				time.sleep(0.04)
			self.client = socketev.socket_ev(self.OnRecv, self.OnSending, self.OnSend, self.OnDisconnect, conn, self.protocolName)
			sppt.write("New client: %s" % self.addressparse(addr))
			
			break
			
			